{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8f7dd688",
   "metadata": {},
   "source": [
    "The LSTM model takes in inputs from the smartphone's sensors (Accelerometer-x,-y,z and Gyroscope-x,y,z) to different driving events (Right turn, Left turn, Accelerating, Braking etc).\n",
    "\n",
    "The model is trained and saved as a Keras file before using TFlite converter to convert into TFLite file to be used in Android Studio. \n",
    "\n",
    "The main issue is not being able to use the Interpreter to determine the accuracy of the TFlite model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a7802d24",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.5.0\n",
      "1.19.5\n",
      "2.5.0\n",
      "1.3.1\n"
     ]
    }
   ],
   "source": [
    "# importing the neccessary libraries\n",
    "# Tensorflow and Keras library\n",
    "###############################################################\n",
    "import tensorflow as tf\n",
    "import seaborn as sns\n",
    "from pylab import rcParams\n",
    "\n",
    "from sklearn import metrics\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import Sequential\n",
    "from tensorflow.keras.layers import Flatten, LSTM, Dense, Dropout, BatchNormalization\n",
    "from keras.regularizers import l2 #regularization function\n",
    "from tensorflow.keras.optimizers import Adam  #perform gradient descent\n",
    "from tensorflow.math import reduce_prod\n",
    "print(tf.__version__)\n",
    "###############################################################\n",
    "# Supporting libraries\n",
    "###############################################################\n",
    "import pandas as pd #used to read dataset and preform dataframe operations\n",
    "import numpy as np  # perform basic array operations\n",
    "import sqlite3      # our raw data is in SQLite form\n",
    "import matplotlib.pyplot as plt #matplotlib\n",
    "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder #s scaler is for normalizing data and label encoder is to label.\n",
    "\n",
    "print(np.__version__)\n",
    "print(tf.__version__)\n",
    "print(pd.__version__)\n",
    "###############################################################\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "sns.set(style = 'whitegrid', palette = 'muted', font_scale = 1.5)\n",
    "rcParams['figure.figsize'] = 14,8\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a30f1210",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>unit</th>\n",
       "      <th>TIME</th>\n",
       "      <th>ACCEL_X</th>\n",
       "      <th>ACCEL_Y</th>\n",
       "      <th>ACCEL_Z</th>\n",
       "      <th>GYRO_X</th>\n",
       "      <th>GYRO_Y</th>\n",
       "      <th>GYRO_Z</th>\n",
       "      <th>CURRENT_SPEED</th>\n",
       "      <th>ACTIVITY</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>06:45:33</td>\n",
       "      <td>0.213084</td>\n",
       "      <td>9.924265</td>\n",
       "      <td>-2.166753</td>\n",
       "      <td>-0.008934</td>\n",
       "      <td>-0.018097</td>\n",
       "      <td>-0.017104</td>\n",
       "      <td>0.0</td>\n",
       "      <td>Right</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>06:45:33</td>\n",
       "      <td>0.213084</td>\n",
       "      <td>9.924265</td>\n",
       "      <td>-2.166753</td>\n",
       "      <td>-0.008934</td>\n",
       "      <td>-0.018097</td>\n",
       "      <td>-0.017104</td>\n",
       "      <td>0.0</td>\n",
       "      <td>Right</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>06:45:33</td>\n",
       "      <td>0.213084</td>\n",
       "      <td>9.924265</td>\n",
       "      <td>-2.166753</td>\n",
       "      <td>-0.008934</td>\n",
       "      <td>-0.018097</td>\n",
       "      <td>-0.017104</td>\n",
       "      <td>0.0</td>\n",
       "      <td>Right</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>06:45:33</td>\n",
       "      <td>0.560243</td>\n",
       "      <td>8.806173</td>\n",
       "      <td>-2.741361</td>\n",
       "      <td>-0.008934</td>\n",
       "      <td>-0.018097</td>\n",
       "      <td>-0.017104</td>\n",
       "      <td>0.0</td>\n",
       "      <td>Right</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>06:45:33</td>\n",
       "      <td>0.193930</td>\n",
       "      <td>9.344869</td>\n",
       "      <td>-1.414973</td>\n",
       "      <td>0.036270</td>\n",
       "      <td>-0.001604</td>\n",
       "      <td>-0.024435</td>\n",
       "      <td>0.0</td>\n",
       "      <td>Right</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   unit      TIME   ACCEL_X   ACCEL_Y   ACCEL_Z    GYRO_X    GYRO_Y    GYRO_Z  \\\n",
       "0     1  06:45:33  0.213084  9.924265 -2.166753 -0.008934 -0.018097 -0.017104   \n",
       "1     2  06:45:33  0.213084  9.924265 -2.166753 -0.008934 -0.018097 -0.017104   \n",
       "2     3  06:45:33  0.213084  9.924265 -2.166753 -0.008934 -0.018097 -0.017104   \n",
       "3     4  06:45:33  0.560243  8.806173 -2.741361 -0.008934 -0.018097 -0.017104   \n",
       "4     5  06:45:33  0.193930  9.344869 -1.414973  0.036270 -0.001604 -0.024435   \n",
       "\n",
       "   CURRENT_SPEED ACTIVITY  \n",
       "0            0.0    Right  \n",
       "1            0.0    Right  \n",
       "2            0.0    Right  \n",
       "3            0.0    Right  \n",
       "4            0.0    Right  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "file = open('Safe_Agro_Data_S10_14_August.db')   ##open the file \n",
    "conn = sqlite3.connect('Safe_Agro_Data_S10_14_August.db')  ## create the cursor pointing to the table\n",
    "data_df = pd.read_sql_query('SELECT * FROM SENSOR_TABLE', conn) #create pandas dataframe so we can manipulate\n",
    "#data_df.insert(0, 'unit', range(1, 1+len(data_df))) # add unit column\n",
    "data_df.insert(0, 'unit', range(1, 1+len(data_df)))\n",
    "data_df.head() # first 5 data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c495d03",
   "metadata": {},
   "source": [
    "### Creating time sequence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "98ce364e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "\n",
    "N_TIME_STEPS = 300\n",
    "N_FEATURES = 6\n",
    "step = 1\n",
    "\n",
    "segments = []\n",
    "labels = []\n",
    "\n",
    "for i in range(0,len(data_df) - N_TIME_STEPS, step):\n",
    "    xs = data_df['ACCEL_X'].values[i: i+N_TIME_STEPS]\n",
    "    ys = data_df['ACCEL_Y'].values[i: i+N_TIME_STEPS]\n",
    "    zs = data_df['ACCEL_Z'].values[i: i+N_TIME_STEPS]\n",
    "    \n",
    "    gxs = data_df['GYRO_X'].values[i: i+N_TIME_STEPS]\n",
    "    gys = data_df['GYRO_Y'].values[i: i+N_TIME_STEPS]\n",
    "    gzs = data_df['GYRO_Z'].values[i: i+N_TIME_STEPS]\n",
    "    \n",
    "    label = stats.mode(data_df['ACTIVITY'][i: i+N_TIME_STEPS])[0][0]\n",
    "    segments.append([xs, ys, zs, gxs, gys, gzs ])\n",
    "    labels.append(label)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "56a38f63",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(128212, 6, 300)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array(segments).shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "39bc280e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(128212,)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array(labels).shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6cefa1b",
   "metadata": {},
   "source": [
    "### Reshaping segments and encoding labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "869054be",
   "metadata": {},
   "outputs": [],
   "source": [
    "# reshape 'segments' to proper format\n",
    "reshaped_segments = np.asarray(segments, dtype = np.float32).reshape(-1, N_TIME_STEPS, N_FEATURES)\n",
    "labels = np.asarray(pd.get_dummies(labels), dtype = np.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "68d98493",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(128212, 300, 6)\n",
      "(128212, 9)\n"
     ]
    }
   ],
   "source": [
    "print(reshaped_segments.shape)\n",
    "print(labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfc22c56",
   "metadata": {},
   "source": [
    "### Splitting dataset into training and testing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "fac9de5e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "RANDOM_SEED = 42\n",
    "X_train, X_test, y_train, y_test = train_test_split(reshaped_segments, labels, test_size= 0.2, random_state=RANDOM_SEED)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "8312b93a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X_train, y_train :  (102569, 300, 6) (102569, 9)\n",
      "X_test, y_test :  (25643, 300, 6) (25643, 9)\n"
     ]
    }
   ],
   "source": [
    "print(\"X_train, y_train : \" , X_train.shape, y_train.shape)\n",
    "print(\"X_test, y_test : \" , X_test.shape, y_test.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97184b7b",
   "metadata": {},
   "source": [
    "### Building LSTM layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "ce008ee5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_1\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "lstm_input_1 (LSTM)          (None, 300, 32)           4992      \n",
      "_________________________________________________________________\n",
      "Dense_2 (Dense)              (None, 300, 32)           1056      \n",
      "_________________________________________________________________\n",
      "batch_normalization_2 (Batch (None, 300, 32)           128       \n",
      "_________________________________________________________________\n",
      "Flatten_3 (Flatten)          (None, 9600)              0         \n",
      "_________________________________________________________________\n",
      "Dense_4 (Dense)              (None, 32)                307232    \n",
      "_________________________________________________________________\n",
      "batch_normalization_3 (Batch (None, 32)                128       \n",
      "_________________________________________________________________\n",
      "output (Dense)               (None, 9)                 297       \n",
      "=================================================================\n",
      "Total params: 313,833\n",
      "Trainable params: 313,705\n",
      "Non-trainable params: 128\n",
      "_________________________________________________________________\n",
      "Wall time: 261 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Building the Model\n",
    "model = Sequential()\n",
    "model.add(LSTM(32,return_sequences = True, input_shape = (X_train.shape[1],X_train.shape[2]),\n",
    "             kernel_regularizer = l2(0.001), bias_regularizer = l2(0.001), name = 'lstm_input_1'))\n",
    "\n",
    "model.add(Dense(32, activation = 'relu', kernel_regularizer=l2(0.001), bias_regularizer = l2(0.001), name = 'Dense_2'))\n",
    "model.add(tf.keras.layers.BatchNormalization())\n",
    "\n",
    "model.add(Flatten(name = 'Flatten_3'))\n",
    "\n",
    "model.add(Dense(32, activation = 'relu', kernel_regularizer=l2(0.001), bias_regularizer = l2(0.001), name = 'Dense_4'))\n",
    "model.add(BatchNormalization())\n",
    "\n",
    "model.add(Dense(9, activation='softmax',\n",
    "               kernel_regularizer=l2(0.001), bias_regularizer = l2(0.001), name = 'output'))\n",
    "\n",
    "# compiling the model\n",
    "model.compile( loss = 'binary_crossentropy', optimizer = Adam(), metrics = ['accuracy'] )\n",
    "len(model.trainable_weights)\n",
    "\n",
    "model.summary()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4870f68",
   "metadata": {},
   "source": [
    "### Model Fitting "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "440e83de",
   "metadata": {},
   "outputs": [],
   "source": [
    "EPOCH_VALUE = 1 #test purposes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "671e9412",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1122/1122 [==============================] - 93s 83ms/step - loss: 0.1284 - accuracy: 0.9835 - val_loss: 0.0761 - val_accuracy: 0.9834\n",
      "Wall time: 1min 32s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Fitting the model\n",
    "history = model.fit(X_train, y_train, epochs=EPOCH_VALUE, batch_size = 64, validation_split=0.3 , shuffle=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12fba496",
   "metadata": {},
   "source": [
    "### Saving model "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "23a747a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "keras_file = \"LSTM_model.h5\"\n",
    "model.save(keras_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67a07ef4",
   "metadata": {},
   "source": [
    "### Convert Keras file into TFlite (using TFLiteConverter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "7453d6ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:absl:Found untraced functions such as lstm_cell_1_layer_call_fn, lstm_cell_1_layer_call_and_return_conditional_losses, lstm_cell_1_layer_call_fn, lstm_cell_1_layer_call_and_return_conditional_losses, lstm_cell_1_layer_call_and_return_conditional_losses while saving (showing 5 of 5). These functions will not be directly callable after loading.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: C:\\Users\\eilha\\AppData\\Local\\Temp\\tmp9xm4_oy4\\assets\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: C:\\Users\\eilha\\AppData\\Local\\Temp\\tmp9xm4_oy4\\assets\n"
     ]
    }
   ],
   "source": [
    "converter = tf.lite.TFLiteConverter.from_keras_model(model)\n",
    "tflite_model = converter.convert()\n",
    "\n",
    "with open('LSTM_model.tflite', 'wb') as f:\n",
    "    f.write(tflite_model)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e54fea6a",
   "metadata": {},
   "source": [
    "### Loading TFlite model to use with Interpreter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "5860f907",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'name': 'serving_default_lstm_input_1_input:0', 'index': 0, 'shape': array([  1, 300,   6]), 'shape_signature': array([ -1, 300,   6]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]\n",
      " \n",
      "[{'name': 'StatefulPartitionedCall:0', 'index': 52, 'shape': array([1, 9]), 'shape_signature': array([-1,  9]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]\n"
     ]
    }
   ],
   "source": [
    "interpreter = tf.lite.Interpreter('LSTM_model.tflite')\n",
    "input_details = interpreter.get_input_details()\n",
    "output_details = interpreter.get_output_details()\n",
    "\n",
    "print(input_details)\n",
    "print(\" \")\n",
    "print(output_details)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77d83984",
   "metadata": {},
   "source": [
    "### evaluate model with testing data (resizing the input and output nodes to match test data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "a8d1e6ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'name': 'serving_default_lstm_input_1_input:0', 'index': 0, 'shape': array([25643,   300,     6]), 'shape_signature': array([ -1, 300,   6]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]\n",
      " \n",
      "[{'name': 'StatefulPartitionedCall:0', 'index': 52, 'shape': array([25643,     9]), 'shape_signature': array([-1,  9]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]\n"
     ]
    }
   ],
   "source": [
    "interpreter.resize_tensor_input(input_details[0]['index'], (25643, 300, 6))\n",
    "interpreter.resize_tensor_input(output_details[0]['index'], (25643, 9))\n",
    "interpreter.allocate_tensors()\n",
    "\n",
    "input_details = interpreter.get_input_details()\n",
    "output_details = interpreter.get_output_details()\n",
    "\n",
    "print(input_details)\n",
    "print(\" \")\n",
    "print(output_details)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d58ca2a5",
   "metadata": {},
   "source": [
    "### Prepare X_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "07d39ebc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(25643, 300, 6)\n",
      "<dtype: 'float32'>\n"
     ]
    }
   ],
   "source": [
    "input_tensor = tf.convert_to_tensor(X_test, np.float32)\n",
    "print(input_tensor.shape)\n",
    "print(input_tensor.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04ff5aa6",
   "metadata": {},
   "source": [
    "### set input_tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "1b8446d4",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "tensorflow/lite/kernels/concatenation.cc:80 t->dims->data[d] != t0->dims->data[d] (25643 != 1)Node number 23 (CONCATENATION) failed to prepare.\nNode number 5 (WHILE) failed to invoke.\n",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-30-6a495971b746>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0minterpreter\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_tensor\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput_details\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'index'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0minput_tensor\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0minterpreter\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0minvoke\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32mC:\\Anaconda\\envs\\tensorflow25py38\\lib\\site-packages\\tensorflow\\lite\\python\\interpreter.py\u001b[0m in \u001b[0;36minvoke\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m    831\u001b[0m     \"\"\"\n\u001b[0;32m    832\u001b[0m     \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_ensure_safe\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 833\u001b[1;33m     \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_interpreter\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mInvoke\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    834\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    835\u001b[0m   \u001b[1;32mdef\u001b[0m \u001b[0mreset_all_variables\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mRuntimeError\u001b[0m: tensorflow/lite/kernels/concatenation.cc:80 t->dims->data[d] != t0->dims->data[d] (25643 != 1)Node number 23 (CONCATENATION) failed to prepare.\nNode number 5 (WHILE) failed to invoke.\n"
     ]
    }
   ],
   "source": [
    "interpreter.set_tensor(input_details[0]['index'], input_tensor)\n",
    "interpreter.invoke()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2df0d01e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
